cli.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. import ast
  2. import inspect
  3. import os
  4. import platform
  5. import re
  6. import sys
  7. import traceback
  8. from functools import update_wrapper
  9. from operator import attrgetter
  10. from threading import Lock
  11. from threading import Thread
  12. import click
  13. from werkzeug.utils import import_string
  14. from .globals import current_app
  15. from .helpers import get_debug_flag
  16. from .helpers import get_env
  17. from .helpers import get_load_dotenv
  18. try:
  19. import dotenv
  20. except ImportError:
  21. dotenv = None
  22. try:
  23. import ssl
  24. except ImportError:
  25. ssl = None # type: ignore
  26. if sys.version_info >= (3, 10):
  27. from importlib import metadata
  28. else:
  29. # Use a backport on Python < 3.10.
  30. #
  31. # We technically have importlib.metadata on 3.8+,
  32. # but the API changed in 3.10, so use the backport
  33. # for consistency.
  34. import importlib_metadata as metadata # type: ignore
  35. class NoAppException(click.UsageError):
  36. """Raised if an application cannot be found or loaded."""
  37. def find_best_app(module):
  38. """Given a module instance this tries to find the best possible
  39. application in the module or raises an exception.
  40. """
  41. from . import Flask
  42. # Search for the most common names first.
  43. for attr_name in ("app", "application"):
  44. app = getattr(module, attr_name, None)
  45. if isinstance(app, Flask):
  46. return app
  47. # Otherwise find the only object that is a Flask instance.
  48. matches = [v for v in module.__dict__.values() if isinstance(v, Flask)]
  49. if len(matches) == 1:
  50. return matches[0]
  51. elif len(matches) > 1:
  52. raise NoAppException(
  53. "Detected multiple Flask applications in module"
  54. f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"
  55. f" to specify the correct one."
  56. )
  57. # Search for app factory functions.
  58. for attr_name in ("create_app", "make_app"):
  59. app_factory = getattr(module, attr_name, None)
  60. if inspect.isfunction(app_factory):
  61. try:
  62. app = app_factory()
  63. if isinstance(app, Flask):
  64. return app
  65. except TypeError as e:
  66. if not _called_with_wrong_args(app_factory):
  67. raise
  68. raise NoAppException(
  69. f"Detected factory {attr_name!r} in module {module.__name__!r},"
  70. " but could not call it without arguments. Use"
  71. f" \"FLASK_APP='{module.__name__}:{attr_name}(args)'\""
  72. " to specify arguments."
  73. ) from e
  74. raise NoAppException(
  75. "Failed to find Flask application or factory in module"
  76. f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"
  77. " to specify one."
  78. )
  79. def _called_with_wrong_args(f):
  80. """Check whether calling a function raised a ``TypeError`` because
  81. the call failed or because something in the factory raised the
  82. error.
  83. :param f: The function that was called.
  84. :return: ``True`` if the call failed.
  85. """
  86. tb = sys.exc_info()[2]
  87. try:
  88. while tb is not None:
  89. if tb.tb_frame.f_code is f.__code__:
  90. # In the function, it was called successfully.
  91. return False
  92. tb = tb.tb_next
  93. # Didn't reach the function.
  94. return True
  95. finally:
  96. # Delete tb to break a circular reference.
  97. # https://docs.python.org/2/library/sys.html#sys.exc_info
  98. del tb
  99. def find_app_by_string(module, app_name):
  100. """Check if the given string is a variable name or a function. Call
  101. a function to get the app instance, or return the variable directly.
  102. """
  103. from . import Flask
  104. # Parse app_name as a single expression to determine if it's a valid
  105. # attribute name or function call.
  106. try:
  107. expr = ast.parse(app_name.strip(), mode="eval").body
  108. except SyntaxError:
  109. raise NoAppException(
  110. f"Failed to parse {app_name!r} as an attribute name or function call."
  111. ) from None
  112. if isinstance(expr, ast.Name):
  113. name = expr.id
  114. args = []
  115. kwargs = {}
  116. elif isinstance(expr, ast.Call):
  117. # Ensure the function name is an attribute name only.
  118. if not isinstance(expr.func, ast.Name):
  119. raise NoAppException(
  120. f"Function reference must be a simple name: {app_name!r}."
  121. )
  122. name = expr.func.id
  123. # Parse the positional and keyword arguments as literals.
  124. try:
  125. args = [ast.literal_eval(arg) for arg in expr.args]
  126. kwargs = {kw.arg: ast.literal_eval(kw.value) for kw in expr.keywords}
  127. except ValueError:
  128. # literal_eval gives cryptic error messages, show a generic
  129. # message with the full expression instead.
  130. raise NoAppException(
  131. f"Failed to parse arguments as literal values: {app_name!r}."
  132. ) from None
  133. else:
  134. raise NoAppException(
  135. f"Failed to parse {app_name!r} as an attribute name or function call."
  136. )
  137. try:
  138. attr = getattr(module, name)
  139. except AttributeError as e:
  140. raise NoAppException(
  141. f"Failed to find attribute {name!r} in {module.__name__!r}."
  142. ) from e
  143. # If the attribute is a function, call it with any args and kwargs
  144. # to get the real application.
  145. if inspect.isfunction(attr):
  146. try:
  147. app = attr(*args, **kwargs)
  148. except TypeError as e:
  149. if not _called_with_wrong_args(attr):
  150. raise
  151. raise NoAppException(
  152. f"The factory {app_name!r} in module"
  153. f" {module.__name__!r} could not be called with the"
  154. " specified arguments."
  155. ) from e
  156. else:
  157. app = attr
  158. if isinstance(app, Flask):
  159. return app
  160. raise NoAppException(
  161. "A valid Flask application was not obtained from"
  162. f" '{module.__name__}:{app_name}'."
  163. )
  164. def prepare_import(path):
  165. """Given a filename this will try to calculate the python path, add it
  166. to the search path and return the actual module name that is expected.
  167. """
  168. path = os.path.realpath(path)
  169. fname, ext = os.path.splitext(path)
  170. if ext == ".py":
  171. path = fname
  172. if os.path.basename(path) == "__init__":
  173. path = os.path.dirname(path)
  174. module_name = []
  175. # move up until outside package structure (no __init__.py)
  176. while True:
  177. path, name = os.path.split(path)
  178. module_name.append(name)
  179. if not os.path.exists(os.path.join(path, "__init__.py")):
  180. break
  181. if sys.path[0] != path:
  182. sys.path.insert(0, path)
  183. return ".".join(module_name[::-1])
  184. def locate_app(module_name, app_name, raise_if_not_found=True):
  185. __traceback_hide__ = True # noqa: F841
  186. try:
  187. __import__(module_name)
  188. except ImportError:
  189. # Reraise the ImportError if it occurred within the imported module.
  190. # Determine this by checking whether the trace has a depth > 1.
  191. if sys.exc_info()[2].tb_next:
  192. raise NoAppException(
  193. f"While importing {module_name!r}, an ImportError was"
  194. f" raised:\n\n{traceback.format_exc()}"
  195. ) from None
  196. elif raise_if_not_found:
  197. raise NoAppException(f"Could not import {module_name!r}.") from None
  198. else:
  199. return
  200. module = sys.modules[module_name]
  201. if app_name is None:
  202. return find_best_app(module)
  203. else:
  204. return find_app_by_string(module, app_name)
  205. def get_version(ctx, param, value):
  206. if not value or ctx.resilient_parsing:
  207. return
  208. import werkzeug
  209. from . import __version__
  210. click.echo(
  211. f"Python {platform.python_version()}\n"
  212. f"Flask {__version__}\n"
  213. f"Werkzeug {werkzeug.__version__}",
  214. color=ctx.color,
  215. )
  216. ctx.exit()
  217. version_option = click.Option(
  218. ["--version"],
  219. help="Show the flask version",
  220. expose_value=False,
  221. callback=get_version,
  222. is_flag=True,
  223. is_eager=True,
  224. )
  225. class DispatchingApp:
  226. """Special application that dispatches to a Flask application which
  227. is imported by name in a background thread. If an error happens
  228. it is recorded and shown as part of the WSGI handling which in case
  229. of the Werkzeug debugger means that it shows up in the browser.
  230. """
  231. def __init__(self, loader, use_eager_loading=None):
  232. self.loader = loader
  233. self._app = None
  234. self._lock = Lock()
  235. self._bg_loading_exc = None
  236. if use_eager_loading is None:
  237. use_eager_loading = os.environ.get("WERKZEUG_RUN_MAIN") != "true"
  238. if use_eager_loading:
  239. self._load_unlocked()
  240. else:
  241. self._load_in_background()
  242. def _load_in_background(self):
  243. # Store the Click context and push it in the loader thread so
  244. # script_info is still available.
  245. ctx = click.get_current_context(silent=True)
  246. def _load_app():
  247. __traceback_hide__ = True # noqa: F841
  248. with self._lock:
  249. if ctx is not None:
  250. click.globals.push_context(ctx)
  251. try:
  252. self._load_unlocked()
  253. except Exception as e:
  254. self._bg_loading_exc = e
  255. t = Thread(target=_load_app, args=())
  256. t.start()
  257. def _flush_bg_loading_exception(self):
  258. __traceback_hide__ = True # noqa: F841
  259. exc = self._bg_loading_exc
  260. if exc is not None:
  261. self._bg_loading_exc = None
  262. raise exc
  263. def _load_unlocked(self):
  264. __traceback_hide__ = True # noqa: F841
  265. self._app = rv = self.loader()
  266. self._bg_loading_exc = None
  267. return rv
  268. def __call__(self, environ, start_response):
  269. __traceback_hide__ = True # noqa: F841
  270. if self._app is not None:
  271. return self._app(environ, start_response)
  272. self._flush_bg_loading_exception()
  273. with self._lock:
  274. if self._app is not None:
  275. rv = self._app
  276. else:
  277. rv = self._load_unlocked()
  278. return rv(environ, start_response)
  279. class ScriptInfo:
  280. """Helper object to deal with Flask applications. This is usually not
  281. necessary to interface with as it's used internally in the dispatching
  282. to click. In future versions of Flask this object will most likely play
  283. a bigger role. Typically it's created automatically by the
  284. :class:`FlaskGroup` but you can also manually create it and pass it
  285. onwards as click object.
  286. """
  287. def __init__(self, app_import_path=None, create_app=None, set_debug_flag=True):
  288. #: Optionally the import path for the Flask application.
  289. self.app_import_path = app_import_path or os.environ.get("FLASK_APP")
  290. #: Optionally a function that is passed the script info to create
  291. #: the instance of the application.
  292. self.create_app = create_app
  293. #: A dictionary with arbitrary data that can be associated with
  294. #: this script info.
  295. self.data = {}
  296. self.set_debug_flag = set_debug_flag
  297. self._loaded_app = None
  298. def load_app(self):
  299. """Loads the Flask app (if not yet loaded) and returns it. Calling
  300. this multiple times will just result in the already loaded app to
  301. be returned.
  302. """
  303. __traceback_hide__ = True # noqa: F841
  304. if self._loaded_app is not None:
  305. return self._loaded_app
  306. if self.create_app is not None:
  307. app = self.create_app()
  308. else:
  309. if self.app_import_path:
  310. path, name = (
  311. re.split(r":(?![\\/])", self.app_import_path, 1) + [None]
  312. )[:2]
  313. import_name = prepare_import(path)
  314. app = locate_app(import_name, name)
  315. else:
  316. for path in ("wsgi.py", "app.py"):
  317. import_name = prepare_import(path)
  318. app = locate_app(import_name, None, raise_if_not_found=False)
  319. if app:
  320. break
  321. if not app:
  322. raise NoAppException(
  323. "Could not locate a Flask application. You did not provide "
  324. 'the "FLASK_APP" environment variable, and a "wsgi.py" or '
  325. '"app.py" module was not found in the current directory.'
  326. )
  327. if self.set_debug_flag:
  328. # Update the app's debug flag through the descriptor so that
  329. # other values repopulate as well.
  330. app.debug = get_debug_flag()
  331. self._loaded_app = app
  332. return app
  333. pass_script_info = click.make_pass_decorator(ScriptInfo, ensure=True)
  334. def with_appcontext(f):
  335. """Wraps a callback so that it's guaranteed to be executed with the
  336. script's application context. If callbacks are registered directly
  337. to the ``app.cli`` object then they are wrapped with this function
  338. by default unless it's disabled.
  339. """
  340. @click.pass_context
  341. def decorator(__ctx, *args, **kwargs):
  342. with __ctx.ensure_object(ScriptInfo).load_app().app_context():
  343. return __ctx.invoke(f, *args, **kwargs)
  344. return update_wrapper(decorator, f)
  345. class AppGroup(click.Group):
  346. """This works similar to a regular click :class:`~click.Group` but it
  347. changes the behavior of the :meth:`command` decorator so that it
  348. automatically wraps the functions in :func:`with_appcontext`.
  349. Not to be confused with :class:`FlaskGroup`.
  350. """
  351. def command(self, *args, **kwargs):
  352. """This works exactly like the method of the same name on a regular
  353. :class:`click.Group` but it wraps callbacks in :func:`with_appcontext`
  354. unless it's disabled by passing ``with_appcontext=False``.
  355. """
  356. wrap_for_ctx = kwargs.pop("with_appcontext", True)
  357. def decorator(f):
  358. if wrap_for_ctx:
  359. f = with_appcontext(f)
  360. return click.Group.command(self, *args, **kwargs)(f)
  361. return decorator
  362. def group(self, *args, **kwargs):
  363. """This works exactly like the method of the same name on a regular
  364. :class:`click.Group` but it defaults the group class to
  365. :class:`AppGroup`.
  366. """
  367. kwargs.setdefault("cls", AppGroup)
  368. return click.Group.group(self, *args, **kwargs)
  369. class FlaskGroup(AppGroup):
  370. """Special subclass of the :class:`AppGroup` group that supports
  371. loading more commands from the configured Flask app. Normally a
  372. developer does not have to interface with this class but there are
  373. some very advanced use cases for which it makes sense to create an
  374. instance of this. see :ref:`custom-scripts`.
  375. :param add_default_commands: if this is True then the default run and
  376. shell commands will be added.
  377. :param add_version_option: adds the ``--version`` option.
  378. :param create_app: an optional callback that is passed the script info and
  379. returns the loaded app.
  380. :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
  381. files to set environment variables. Will also change the working
  382. directory to the directory containing the first file found.
  383. :param set_debug_flag: Set the app's debug flag based on the active
  384. environment
  385. .. versionchanged:: 1.0
  386. If installed, python-dotenv will be used to load environment variables
  387. from :file:`.env` and :file:`.flaskenv` files.
  388. """
  389. def __init__(
  390. self,
  391. add_default_commands=True,
  392. create_app=None,
  393. add_version_option=True,
  394. load_dotenv=True,
  395. set_debug_flag=True,
  396. **extra,
  397. ):
  398. params = list(extra.pop("params", None) or ())
  399. if add_version_option:
  400. params.append(version_option)
  401. AppGroup.__init__(self, params=params, **extra)
  402. self.create_app = create_app
  403. self.load_dotenv = load_dotenv
  404. self.set_debug_flag = set_debug_flag
  405. if add_default_commands:
  406. self.add_command(run_command)
  407. self.add_command(shell_command)
  408. self.add_command(routes_command)
  409. self._loaded_plugin_commands = False
  410. def _load_plugin_commands(self):
  411. if self._loaded_plugin_commands:
  412. return
  413. for ep in metadata.entry_points(group="flask.commands"):
  414. self.add_command(ep.load(), ep.name)
  415. self._loaded_plugin_commands = True
  416. def get_command(self, ctx, name):
  417. self._load_plugin_commands()
  418. # Look up built-in and plugin commands, which should be
  419. # available even if the app fails to load.
  420. rv = super().get_command(ctx, name)
  421. if rv is not None:
  422. return rv
  423. info = ctx.ensure_object(ScriptInfo)
  424. # Look up commands provided by the app, showing an error and
  425. # continuing if the app couldn't be loaded.
  426. try:
  427. return info.load_app().cli.get_command(ctx, name)
  428. except NoAppException as e:
  429. click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
  430. def list_commands(self, ctx):
  431. self._load_plugin_commands()
  432. # Start with the built-in and plugin commands.
  433. rv = set(super().list_commands(ctx))
  434. info = ctx.ensure_object(ScriptInfo)
  435. # Add commands provided by the app, showing an error and
  436. # continuing if the app couldn't be loaded.
  437. try:
  438. rv.update(info.load_app().cli.list_commands(ctx))
  439. except NoAppException as e:
  440. # When an app couldn't be loaded, show the error message
  441. # without the traceback.
  442. click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")
  443. except Exception:
  444. # When any other errors occurred during loading, show the
  445. # full traceback.
  446. click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")
  447. return sorted(rv)
  448. def main(self, *args, **kwargs):
  449. # Set a global flag that indicates that we were invoked from the
  450. # command line interface. This is detected by Flask.run to make the
  451. # call into a no-op. This is necessary to avoid ugly errors when the
  452. # script that is loaded here also attempts to start a server.
  453. os.environ["FLASK_RUN_FROM_CLI"] = "true"
  454. if get_load_dotenv(self.load_dotenv):
  455. load_dotenv()
  456. obj = kwargs.get("obj")
  457. if obj is None:
  458. obj = ScriptInfo(
  459. create_app=self.create_app, set_debug_flag=self.set_debug_flag
  460. )
  461. kwargs["obj"] = obj
  462. kwargs.setdefault("auto_envvar_prefix", "FLASK")
  463. return super().main(*args, **kwargs)
  464. def _path_is_ancestor(path, other):
  465. """Take ``other`` and remove the length of ``path`` from it. Then join it
  466. to ``path``. If it is the original value, ``path`` is an ancestor of
  467. ``other``."""
  468. return os.path.join(path, other[len(path) :].lstrip(os.sep)) == other
  469. def load_dotenv(path=None):
  470. """Load "dotenv" files in order of precedence to set environment variables.
  471. If an env var is already set it is not overwritten, so earlier files in the
  472. list are preferred over later files.
  473. This is a no-op if `python-dotenv`_ is not installed.
  474. .. _python-dotenv: https://github.com/theskumar/python-dotenv#readme
  475. :param path: Load the file at this location instead of searching.
  476. :return: ``True`` if a file was loaded.
  477. .. versionchanged:: 1.1.0
  478. Returns ``False`` when python-dotenv is not installed, or when
  479. the given path isn't a file.
  480. .. versionchanged:: 2.0
  481. When loading the env files, set the default encoding to UTF-8.
  482. .. versionadded:: 1.0
  483. """
  484. if dotenv is None:
  485. if path or os.path.isfile(".env") or os.path.isfile(".flaskenv"):
  486. click.secho(
  487. " * Tip: There are .env or .flaskenv files present."
  488. ' Do "pip install python-dotenv" to use them.',
  489. fg="yellow",
  490. err=True,
  491. )
  492. return False
  493. # if the given path specifies the actual file then return True,
  494. # else False
  495. if path is not None:
  496. if os.path.isfile(path):
  497. return dotenv.load_dotenv(path, encoding="utf-8")
  498. return False
  499. new_dir = None
  500. for name in (".env", ".flaskenv"):
  501. path = dotenv.find_dotenv(name, usecwd=True)
  502. if not path:
  503. continue
  504. if new_dir is None:
  505. new_dir = os.path.dirname(path)
  506. dotenv.load_dotenv(path, encoding="utf-8")
  507. return new_dir is not None # at least one file was located and loaded
  508. def show_server_banner(env, debug, app_import_path, eager_loading):
  509. """Show extra startup messages the first time the server is run,
  510. ignoring the reloader.
  511. """
  512. if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
  513. return
  514. if app_import_path is not None:
  515. message = f" * Serving Flask app {app_import_path!r}"
  516. if not eager_loading:
  517. message += " (lazy loading)"
  518. click.echo(message)
  519. click.echo(f" * Environment: {env}")
  520. if env == "production":
  521. click.secho(
  522. " WARNING: This is a development server. Do not use it in"
  523. " a production deployment.",
  524. fg="red",
  525. )
  526. click.secho(" Use a production WSGI server instead.", dim=True)
  527. if debug is not None:
  528. click.echo(f" * Debug mode: {'on' if debug else 'off'}")
  529. class CertParamType(click.ParamType):
  530. """Click option type for the ``--cert`` option. Allows either an
  531. existing file, the string ``'adhoc'``, or an import for a
  532. :class:`~ssl.SSLContext` object.
  533. """
  534. name = "path"
  535. def __init__(self):
  536. self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True)
  537. def convert(self, value, param, ctx):
  538. if ssl is None:
  539. raise click.BadParameter(
  540. 'Using "--cert" requires Python to be compiled with SSL support.',
  541. ctx,
  542. param,
  543. )
  544. try:
  545. return self.path_type(value, param, ctx)
  546. except click.BadParameter:
  547. value = click.STRING(value, param, ctx).lower()
  548. if value == "adhoc":
  549. try:
  550. import cryptography # noqa: F401
  551. except ImportError:
  552. raise click.BadParameter(
  553. "Using ad-hoc certificates requires the cryptography library.",
  554. ctx,
  555. param,
  556. ) from None
  557. return value
  558. obj = import_string(value, silent=True)
  559. if isinstance(obj, ssl.SSLContext):
  560. return obj
  561. raise
  562. def _validate_key(ctx, param, value):
  563. """The ``--key`` option must be specified when ``--cert`` is a file.
  564. Modifies the ``cert`` param to be a ``(cert, key)`` pair if needed.
  565. """
  566. cert = ctx.params.get("cert")
  567. is_adhoc = cert == "adhoc"
  568. is_context = ssl and isinstance(cert, ssl.SSLContext)
  569. if value is not None:
  570. if is_adhoc:
  571. raise click.BadParameter(
  572. 'When "--cert" is "adhoc", "--key" is not used.', ctx, param
  573. )
  574. if is_context:
  575. raise click.BadParameter(
  576. 'When "--cert" is an SSLContext object, "--key is not used.', ctx, param
  577. )
  578. if not cert:
  579. raise click.BadParameter('"--cert" must also be specified.', ctx, param)
  580. ctx.params["cert"] = cert, value
  581. else:
  582. if cert and not (is_adhoc or is_context):
  583. raise click.BadParameter('Required when using "--cert".', ctx, param)
  584. return value
  585. class SeparatedPathType(click.Path):
  586. """Click option type that accepts a list of values separated by the
  587. OS's path separator (``:``, ``;`` on Windows). Each value is
  588. validated as a :class:`click.Path` type.
  589. """
  590. def convert(self, value, param, ctx):
  591. items = self.split_envvar_value(value)
  592. super_convert = super().convert
  593. return [super_convert(item, param, ctx) for item in items]
  594. @click.command("run", short_help="Run a development server.")
  595. @click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.")
  596. @click.option("--port", "-p", default=5000, help="The port to bind to.")
  597. @click.option(
  598. "--cert",
  599. type=CertParamType(),
  600. help="Specify a certificate file to use HTTPS.",
  601. is_eager=True,
  602. )
  603. @click.option(
  604. "--key",
  605. type=click.Path(exists=True, dir_okay=False, resolve_path=True),
  606. callback=_validate_key,
  607. expose_value=False,
  608. help="The key file to use when specifying a certificate.",
  609. )
  610. @click.option(
  611. "--reload/--no-reload",
  612. default=None,
  613. help="Enable or disable the reloader. By default the reloader "
  614. "is active if debug is enabled.",
  615. )
  616. @click.option(
  617. "--debugger/--no-debugger",
  618. default=None,
  619. help="Enable or disable the debugger. By default the debugger "
  620. "is active if debug is enabled.",
  621. )
  622. @click.option(
  623. "--eager-loading/--lazy-loading",
  624. default=None,
  625. help="Enable or disable eager loading. By default eager "
  626. "loading is enabled if the reloader is disabled.",
  627. )
  628. @click.option(
  629. "--with-threads/--without-threads",
  630. default=True,
  631. help="Enable or disable multithreading.",
  632. )
  633. @click.option(
  634. "--extra-files",
  635. default=None,
  636. type=SeparatedPathType(),
  637. help=(
  638. "Extra files that trigger a reload on change. Multiple paths"
  639. f" are separated by {os.path.pathsep!r}."
  640. ),
  641. )
  642. @click.option(
  643. "--exclude-patterns",
  644. default=None,
  645. type=SeparatedPathType(),
  646. help=(
  647. "Files matching these fnmatch patterns will not trigger a reload"
  648. " on change. Multiple patterns are separated by"
  649. f" {os.path.pathsep!r}."
  650. ),
  651. )
  652. @pass_script_info
  653. def run_command(
  654. info,
  655. host,
  656. port,
  657. reload,
  658. debugger,
  659. eager_loading,
  660. with_threads,
  661. cert,
  662. extra_files,
  663. exclude_patterns,
  664. ):
  665. """Run a local development server.
  666. This server is for development purposes only. It does not provide
  667. the stability, security, or performance of production WSGI servers.
  668. The reloader and debugger are enabled by default if
  669. FLASK_ENV=development or FLASK_DEBUG=1.
  670. """
  671. debug = get_debug_flag()
  672. if reload is None:
  673. reload = debug
  674. if debugger is None:
  675. debugger = debug
  676. show_server_banner(get_env(), debug, info.app_import_path, eager_loading)
  677. app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)
  678. from werkzeug.serving import run_simple
  679. run_simple(
  680. host,
  681. port,
  682. app,
  683. use_reloader=reload,
  684. use_debugger=debugger,
  685. threaded=with_threads,
  686. ssl_context=cert,
  687. extra_files=extra_files,
  688. exclude_patterns=exclude_patterns,
  689. )
  690. @click.command("shell", short_help="Run a shell in the app context.")
  691. @with_appcontext
  692. def shell_command() -> None:
  693. """Run an interactive Python shell in the context of a given
  694. Flask application. The application will populate the default
  695. namespace of this shell according to its configuration.
  696. This is useful for executing small snippets of management code
  697. without having to manually configure the application.
  698. """
  699. import code
  700. from .globals import _app_ctx_stack
  701. app = _app_ctx_stack.top.app
  702. banner = (
  703. f"Python {sys.version} on {sys.platform}\n"
  704. f"App: {app.import_name} [{app.env}]\n"
  705. f"Instance: {app.instance_path}"
  706. )
  707. ctx: dict = {}
  708. # Support the regular Python interpreter startup script if someone
  709. # is using it.
  710. startup = os.environ.get("PYTHONSTARTUP")
  711. if startup and os.path.isfile(startup):
  712. with open(startup) as f:
  713. eval(compile(f.read(), startup, "exec"), ctx)
  714. ctx.update(app.make_shell_context())
  715. # Site, customize, or startup script can set a hook to call when
  716. # entering interactive mode. The default one sets up readline with
  717. # tab and history completion.
  718. interactive_hook = getattr(sys, "__interactivehook__", None)
  719. if interactive_hook is not None:
  720. try:
  721. import readline
  722. from rlcompleter import Completer
  723. except ImportError:
  724. pass
  725. else:
  726. # rlcompleter uses __main__.__dict__ by default, which is
  727. # flask.__main__. Use the shell context instead.
  728. readline.set_completer(Completer(ctx).complete)
  729. interactive_hook()
  730. code.interact(banner=banner, local=ctx)
  731. @click.command("routes", short_help="Show the routes for the app.")
  732. @click.option(
  733. "--sort",
  734. "-s",
  735. type=click.Choice(("endpoint", "methods", "rule", "match")),
  736. default="endpoint",
  737. help=(
  738. 'Method to sort routes by. "match" is the order that Flask will match '
  739. "routes when dispatching a request."
  740. ),
  741. )
  742. @click.option("--all-methods", is_flag=True, help="Show HEAD and OPTIONS methods.")
  743. @with_appcontext
  744. def routes_command(sort: str, all_methods: bool) -> None:
  745. """Show all registered routes with endpoints and methods."""
  746. rules = list(current_app.url_map.iter_rules())
  747. if not rules:
  748. click.echo("No routes were registered.")
  749. return
  750. ignored_methods = set(() if all_methods else ("HEAD", "OPTIONS"))
  751. if sort in ("endpoint", "rule"):
  752. rules = sorted(rules, key=attrgetter(sort))
  753. elif sort == "methods":
  754. rules = sorted(rules, key=lambda rule: sorted(rule.methods)) # type: ignore
  755. rule_methods = [
  756. ", ".join(sorted(rule.methods - ignored_methods)) # type: ignore
  757. for rule in rules
  758. ]
  759. headers = ("Endpoint", "Methods", "Rule")
  760. widths = (
  761. max(len(rule.endpoint) for rule in rules),
  762. max(len(methods) for methods in rule_methods),
  763. max(len(rule.rule) for rule in rules),
  764. )
  765. widths = [max(len(h), w) for h, w in zip(headers, widths)]
  766. row = "{{0:<{0}}} {{1:<{1}}} {{2:<{2}}}".format(*widths)
  767. click.echo(row.format(*headers).strip())
  768. click.echo(row.format(*("-" * width for width in widths)))
  769. for rule, methods in zip(rules, rule_methods):
  770. click.echo(row.format(rule.endpoint, methods, rule.rule).rstrip())
  771. cli = FlaskGroup(
  772. help="""\
  773. A general utility script for Flask applications.
  774. Provides commands from Flask, extensions, and the application. Loads the
  775. application defined in the FLASK_APP environment variable, or from a wsgi.py
  776. file. Setting the FLASK_ENV environment variable to 'development' will enable
  777. debug mode.
  778. \b
  779. {prefix}{cmd} FLASK_APP=hello.py
  780. {prefix}{cmd} FLASK_ENV=development
  781. {prefix}flask run
  782. """.format(
  783. cmd="export" if os.name == "posix" else "set",
  784. prefix="$ " if os.name == "posix" else "> ",
  785. )
  786. )
  787. def main() -> None:
  788. cli.main()
  789. if __name__ == "__main__":
  790. main()